<?php
class Application_Model_Date {

	private static function calcOffset( $offsetSec ) {
		$sec = $offsetSec;
		if( $offsetSec < 0 ) {
			$sign = '-';
		} else {
			$sign = '+';
		}
		$offsetSec = abs( $offsetSec );
		$min = $offsetSec / 60;
		$hour = 0;
		while( $min >= 60 ) {
			$hour++;
			$min -= 60;
		}

		$GMTOffset = floatval( $sign . $hour . "." . round( $min * 10 / 60 ) );

		if( $hour < 10 ) {
			$hour = '0' . $hour;
		}
		if( $min < 10 ) {
			$min = '0' . $min;
		}
		return array(
                'str'        => $sign . $hour . ":" . $min,
                'h'          => $hour,
                'm'          => $min,
                'sign'       => $sign,
                'sec'        => $sec,
                'gmtOffsetDB'=> $GMTOffset );
	}

	public static function  getOffset( $time_zone ) {
		if( ( $time_zone == 'NULL' ) || empty( $time_zone ) ) {
			return false;
		}
		try {
			$tz = new DateTimeZone( $time_zone );
		} catch( Exception $e ) {
			return false;
		}
		$dt = new DateTime( 'now', $tz );
		return self::calcOffset( $dt->getOffset() );
	}

	public static function convertGMTtoUnix( $GMT ) {
		if( empty( $GMT ) ) {
			return 0;
		}
		$GMT = floatval( $GMT );
		return ( $GMT * 60 * 60 );
	}

	public static function convertDateByLocaleToGMT($date,$locale){
		$date=new DateTime($date, new DateTimeZone($locale));
		return gmdate ('Y-m-d H:i:s', $date->getTimestamp());
	}

	public static function convertDateByZoneToGMT($date,$zone){
		$date=new DateTime($date, new DateTimeZone('GMT0'));
		$zone=floatval($zone);
		$date->setTimestamp($date->getTimestamp() +$zone*60*60);
		return gmdate ('Y-m-d H:i:s', $date->getTimestamp());
	}

	public static function convertDateToGMT($date,$locale,$zone){
		if($locale) return  self::convertDateByLocaleToGMT($date, $locale);
		else return self::convertDateByZoneToGMT($date, $zone);
	}

	public static function convertDateToGMTScheduler($startDate,$endDate,$hour, $locale,$zone){			
		$startDateFull=$startDate." ".$hour.":00";
		$endDateFull=$endDate." ".$hour.":00";
		
		$result['startDate']=substr(self::convertDateToGMT($startDateFull, $locale, $zone),0,-9);
		$result['endDate']=substr(self::convertDateToGMT($endDateFull, $locale, $zone),0,-9);
		$result['hour']=substr(self::convertDateToGMT($startDateFull, $locale, $zone), 11,-3);
		return $result;
	}

    public static function getTimeObjectRelativelyUserTimeZoneOrUserLocale( $timeobj, $timezone, $locale ) {
        if( empty( $locale )) {
            return $timeobj->modify( '+' . intval( $timezone ) . ' hours' );
        } else {
            $offset = new DateTimeZone( $locale );
            return $timeobj->modify( '+' . $offset->getOffset( $timeobj ) . ' seconds' );
        }
    }
}
